<?php
namespace app\pay\controller;
use think\Controller;
use think\Request;
use think\Config;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\ExecutePayment;
use think\Db;
use fast\Random;

class Paymenttion extends  Controller
{
    public function paypal($xtmoney,$money,$userid,$bz='USD'){
        $clientId = 'AS0Tr_UyrEGR6TTQ48SRBLsGP-3yf7DLJ1a2qbjR_FCsHLHOlakWnuvVTHuty_gjG85u_SFZxKYGKKEB';
        $clientSecret = 'EPPMj0RxcjnFKvN2S9KHec_xT5zEWFmtJfJLnb8tK9EIrnYOGrEMHT04Fo3izghIi1hK5v8wWiVF0-m9';
//        $clientId='AXGZVTjhw2zxUaXMEF2ocxdMrOL2dvaqmZLfbzUgWuH_WNsvveZOHLNml6KDvyCN85G6D3jwku_4n_dY';
//        $clientSecret='EM7T7JmK3R0zOEDTiD8W0Iatew92-2hPuv_m52ofDtxK14hZPixaab4q0z67NhuRq9OaRjSy7wTzu7AA';
        $apiContext = new ApiContext(
            new OAuthTokenCredential(
                $clientId,
                $clientSecret
            )
        );
        $apiContext->setConfig(
            array(
                'mode' => 'live',
                'log.LogEnabled' => true,
                'log.FileName' => '../PayPal.log',
                'log.LogLevel' => 'INFO', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
                'cache.enabled' => true,
                // 'http.CURLOPT_CONNECTTIMEOUT' => 30
                // 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'
                //'log.AdapterFactory' => '\PayPal\Log\DefaultLogFactory' // Factory class implementing \PayPal\Log\PayPalLogFactory
            )
        );

        // # # #付款人
        //一种代表付款人的资源。
        // paypal账户支付，设置支付方式。
        //“贝宝”。
        $price=$money;
        $payer = new Payer();
        $payer->setPaymentMethod("paypal");

        //# # #项目信息
        //(可选)让您指定项明智。
        //信息
        $item = new Item();
        $item->setName('test pro 1')
            ->setCurrency($bz)
            ->setQuantity(1)
            ->setSku($userid) // Similar to `item_number` in Classic API "testpro1_01"
            ->setDescription($xtmoney)
            ->setPrice($price);


        $itemList = new ItemList();
        $itemList->setItems(array($item));

        // 自定义用户收货地址，避免用户在paypal上账单的收货地址和销售方收货地址有出入
        // 这里定义了收货地址，用户在支付过程中就不能更改收货地址，否则，用户可以自己更改收货地址
//        $address = new ShippingAddress();
//        $address->setRecipientName('什么名字')
//            ->setLine1('什么街什么路什么小区')
//            ->setLine2('什么单元什么号')
//            ->setCity('城市名')
//            ->setState('浙江省')
//            ->setPhone('12345678911')
//            ->setPostalCode('12345')
//            ->setCountryCode('CN');
//
//        $itemList->setShippingAddress($address);


        // ##额外的付款细节。
        //使用此可选字段设置附加。
        //付款信息，如税务、航运等。
        //费用等。
        $details = new Details();
        $details->setShipping(0)
            ->setSubtotal($price);

        // # # #
        //您可以指定付款金额。
        //你还可以指定额外的细节。
        //例如航运，税。
        $amount = new Amount();
        $amount->setCurrency($bz)
            ->setTotal($price)
            ->setDetails($details);

        // # # #事务
        //交易定义了A的合同。
        //付款-什么是付款?
        //实现它。
        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription("Payment description")
            ->setInvoiceNumber(uniqid());

        // # # #重定向url
        //设置买家必须重定向到的url。
        //审批/取消付款。
        $baseUrl ='http://api.91ggjf.cn/';
        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl("$baseUrl/pay/index/exec?success=true")
            ->setCancelUrl("$baseUrl/pay/index/cancel?success=false");

        // # # #付款
        // 支付资源;创建一个使用
        //上述类型及意图“出售”
        $payment = new Payment();
        $payment->setIntent("sale")
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions(array($transaction));

        $payment->create($apiContext);

        $approvalUrl = $payment->getApprovalLink();

        return ["code"=>200,'url'=>$approvalUrl];

    }

    public function weixinpay(){

    }

    public function duihuan($money,$from,$to){

        $host = "http://jisuhuilv.market.alicloudapi.com";
        $path = "/exchange/convert";
        $method = "GET";
        $appcode = "934d780b78a545b1b4b2d3aabe5cb2be";  //appcode
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "amount=".$money."&from=".$from."&to=".$to;
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        return curl_exec($curl);

    }

    public function ceshi(){
        $file = fopen("pos/test.txt","w");



        fwrite($file,'ok');

    }

    public function pos_callback(Request $request){

        $orgTxnType=$request->param("orgTxnType");
        $orgExternalTraceNo=$request->param("orgExternalTraceNo");
        $processFlag=$request->param("processFlag");
        $txnType=$request->param("txnType");
        $amt=$request->param("amt");
        $externalTraceNo=$request->param("externalTraceNo");
        $terminalOperId=$request->param("terminalOperId");
        $authCode=$request->param("authCode");
        $RRN=$request->param("RRN");
        $txnTime=$request->param("txnTime");
        $shortPAN=$request->param("shortPAN");
        $responseCode=$request->param("responseCode");
        $responseMessage=$request->param("responseMessage");
        $cardType=$request->param("cardType");
        $issuerId=$request->param("issuerId");
        $issuerIdView=$request->param("issuerIdView");

        $signature=$request->param("signature");
//$signature="rdnuykzCmurAT6LzE4SGPjDeSoJa/nuKmikAKbwZM+b4UcFxfVVekiw2RIqEWFF/vopi01+OWnkS8CPzrpf3oKAaDk1RHkh9n4ZytvjUrrTdmmV3TYcN0mG8OGexi9hYTMy/Fj1km7EIvdgr0OAQ3wDfg5ai44aNAt6oWP8G9FM=";

        $signature=base64_decode($signature);

        $data=$processFlag.$txnType.$amt.$externalTraceNo.$terminalOperId.$authCode.$RRN.$txnTime.$shortPAN.$responseCode.$cardType.$issuerId;
//$data="0PUR7768.0000100126852010620151020 103103622658893800000103030000";


        $fp = fopen("pos/vposPHP.cer", "r");
        $cert = fread($fp, 8192);
        fclose($fp);
        $pubkeyid = openssl_get_publickey($cert);


        $ok = openssl_verify($data, $signature, $pubkeyid);

        $file = fopen("pos/test.txt","w");

        if ($ok == 1) {

            fwrite($file,$externalTraceNo);

            $charge=db("capital_charge")->where("number",$externalTraceNo)->find();

            if($charge){

                db("capital_charge")->where("number",$externalTraceNo)->update(["status"=>2]);
                $capitaldata=db("capital")->where("uid",$charge['uid'])->find();
                $now_wallet=$capitaldata['wallet']+$charge['money'];
                db("capital")->where("uid",$charge['uid'])->update(["wallet"=>$now_wallet]);
            }

            echo '0';
        } elseif ($ok == 0) {

            fwrite($file,'no');
            echo '1';
        } else {

            fwrite($file,'never');
            echo '0';
        }
    }

    public function pos_add_num($user_id,$money){


        $number=Random::numeric(16);
        $investdata = ['uid' => $user_id, 'money' => $money,'source'=>3,'number'=>$number,'addtime'=>time(),'status'=>1];
        Db::table('t_capital_charge')->insert($investdata);
        return $number;

    }

    public function pos_oqs(Request $request){

        $mermbercode="812445073920087";


        $r_orderId=$request->param("orderId");
        $r_reqTime=$request->param("reqTime");
        $r_ext1=$request->param("ext1");
        $r_ext2=$request->param("ext2");
        $r_MAC=$request->param("MAC");;




        $r_sign='orderId='.$r_orderId.'reqTime='.$r_reqTime;


// 将 MAC  进行 decode 处理

        $MAC=base64_decode($r_MAC);
        $filess1 = fopen("pos/test2.txt","w");
        fwrite($filess1,$r_MAC);
        fclose($filess1);

        $fp = fopen("pos/mgw.pem", "r");
        $cert = fread($fp, 8192);
        fclose($fp);

        $pubkeyid = openssl_get_publickey($cert);


        $ok = openssl_verify($r_sign, $MAC, $pubkeyid);
        $filess2 = fopen("pos/test3.txt","w");
        fwrite($filess2,$ok);
        fclose($filess2);

        if($ok == 1){
            $r_djuge='<h1><font color=green>TRUE</font></h1>';

            $reqTime=$request->param("reqTime");
            $respTime=date("YmdHis");
            $responseCode="00";
//00 –  请求成功
//56 –  无此记录
//96 –  系统异常
//其他  –  失败


            $orderId=$request->param("orderId");

            $merchantId=$mermbercode;

            $orderinfo=db("capital_charge")->where("number",$orderId)->find();



            $merchantName=$orderinfo['uid'];

            $currency_config=Config::get('currency');

            $currency0=$currency_config[1][0];                         // 获取进货率

            $money=$orderinfo['money']*$currency0;  //转换人民币
            $amt=number_format($money,2);



            $ext_address='深圳富侨';
            $ext_orderId=date("YmdHis");
//$fp=fopen($reqTime.'_'.$orderId,'w');
            $xml_sign='<MessageContent><reqTime>'.$reqTime.'</reqTime><respTime>'.$respTime.'</respTime><responseCode>'.$responseCode.'</responseCode><message><orderId>'.$orderId.'</orderId><merchantId>'.$merchantId.'</merchantId><merchantName>'.$merchantName.'</merchantName><amt>'.$amt.'</amt><amt2></amt2><amt3></amt3><amt4></amt4><ext><orderId><value>'.$ext_orderId.'</value><chnName>订单号</chnName></orderId><address><value>'.$ext_address.'</value><chnName>收件人地址</chnName></address></ext></message></MessageContent>';

            $filess7 = fopen("pos/test7.txt","w");
            fwrite($filess7,$xml_sign);
            fclose($filess7);

            // fetch private key from file and ready it

            $pem_path='pos/81244507392008790.pem';


            $fp = fopen($pem_path, "r");

            $priv_key = fread($fp, 8192);
            fclose($fp);
            $pkeyid = openssl_get_privatekey($priv_key);

// compute signature
            $openssl=openssl_sign($xml_sign, $signMsg, $pkeyid,OPENSSL_ALGO_SHA1);

            $filess8 = fopen("pos/test8.txt","w");
            fwrite($filess8,$openssl);
            fclose($filess8);


// free the key from memory
            openssl_free_key($pkeyid);

            $MAC = base64_encode($signMsg);


//\\

            $xml_info='<?xml version="1.0" encoding="UTF-8"?><ResponseMessage><MAC>'.$MAC.'</MAC>'.$xml_sign.'</ResponseMessage>';
            $filess9 = fopen("pos/test9.txt","w");
            fwrite($filess9,$xml_info);
            fclose($filess9);
            return $xml_info;

        }else{
            $r_djuge='<h1><font color=red>FALSE</font></h1>';
        }





    }

}